package com.laundry.user.data.database

import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import android.content.Context
import com.laundry.user.data.model.*

/**
 * 洗护帮数据库
 */
@Database(
    entities = [
        User::class,
        ServiceCategory::class,
        Merchant::class,
        Service::class,
        Order::class,
        Review::class,
        Coupon::class,
        ChatSession::class,
        ChatMessage::class,
        Notification::class,
        Favorite::class,
        Address::class,
        SearchHistory::class
    ],
    version = 1,
    exportSchema = false
)
@TypeConverters(Converters::class)
abstract class LaundryDatabase : RoomDatabase() {
    
    abstract fun userDao(): UserDao
    abstract fun serviceCategoryDao(): ServiceCategoryDao
    abstract fun merchantDao(): MerchantDao
    abstract fun serviceDao(): ServiceDao
    abstract fun orderDao(): OrderDao
    abstract fun reviewDao(): ReviewDao
    abstract fun couponDao(): CouponDao
    abstract fun chatDao(): ChatDao
    abstract fun notificationDao(): NotificationDao
    abstract fun favoriteDao(): FavoriteDao
    abstract fun addressDao(): AddressDao
    abstract fun searchHistoryDao(): SearchHistoryDao
    
    companion object {
        @Volatile
        private var INSTANCE: LaundryDatabase? = null
        
        fun getDatabase(context: Context): LaundryDatabase {
            return INSTANCE ?: synchronized(this) {
                val instance = Room.databaseBuilder(
                    context.applicationContext,
                    LaundryDatabase::class.java,
                    "laundry_database"
                )
                    .fallbackToDestructiveMigration()
                    .build()
                INSTANCE = instance
                instance
            }
        }
    }
}

/**
 * 类型转换器
 */
class Converters {
    
    @androidx.room.TypeConverter
    fun fromStringList(value: List<String>): String {
        return value.joinToString(",")
    }
    
    @androidx.room.TypeConverter
    fun toStringList(value: String): List<String> {
        return if (value.isEmpty()) emptyList() else value.split(",")
    }
    
    @androidx.room.TypeConverter
    fun fromOrderItemList(value: List<OrderItem>): String {
        return com.google.gson.Gson().toJson(value)
    }
    
    @androidx.room.TypeConverter
    fun toOrderItemList(value: String): List<OrderItem> {
        return if (value.isEmpty()) {
            emptyList()
        } else {
            com.google.gson.Gson().fromJson(
                value,
                object : com.google.gson.reflect.TypeToken<List<OrderItem>>() {}.type
            )
        }
    }
}
